<?php 

namespace App\Services;

use Illuminate\Support\Collection;

/**
* @des PHP生成无限多级分类
*/
class PHPTree
{
	// 默认的配置
	protected $config = array(
        'id'       => 'id',           // 主键
        'pid'      => 'pid',          // 父键
        'children' => 'children',     // 子类标示
        'root'     => 0 
    );

    // ID索引后的数据
    protected $dataId = array();

	public function __construct($data=[], array $option = array())
    {
    	if (!empty($option)) {
    		$this->config = array_merge($this->config, $option);
    	}

        if ($data instanceof Collection) {
           $data = $data->toArray(); 
        }

    	$this->data = $data;

    }

    public function set($option)
    {
		$this->config = array_merge($this->config, $option);
    }
   
    // 
    public function makeId($data, $id)
    {
    	$array = array();

		foreach ($data as $key=>$value) {
			$array[$value[$id]] = $data[$key];
		}

		return $array;
    }

    // 获取ID索引后的数据
    public function getDataId()
    {
        return $this->dataId;
    }

    // 渲染数据
    public function render($data=[], $option = [])
    {	
    	$data = $data ?: $this->data;

    	if (empty($data)) {
    		return array();
    	}

    	$config = $option ? array_merge($this->config, $option) : $this->config;
    	extract($config);

    	$tree = array(); // 返回树

        $data = $this->dataId = $this->makeId($data, $id);

		foreach ($data as $key=>$value) {
			$parentId = $value[$pid];
			if ($root == $parentId) {
				$tree[$value[$id]] = &$data[$key];
			} else {
				if (isset($data[$parentId])) {
					$parent = &$data[$parentId];
					$parent[$children][$value[$id]] = &$data[$key];
				}
			}
		}

		return $tree;
    }
}	